package com.zr.websocket;


import com.zr.service.sys.SysLogService;

import com.zr.utils.RedisUtil;
import com.zr.utils.TokenUtil;
import com.zr.vo.LoginUser;
import com.zr.vo.sys.SysLog;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;

import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Date;

@Component
@ServerEndpoint(value = "/loginLogSocket/{token}")
public class LoginLogSocket {

    private String token;

    private static RedisUtil redisUtil;

    private static SysLogService sysLogService;


    @Autowired
    public  void setRedisUtil(RedisUtil redisUtil) {
        LoginLogSocket.redisUtil = redisUtil;
    }

    @Autowired
    public void setSysLogService(SysLogService sysLogService) {
        LoginLogSocket.sysLogService = sysLogService;
    }

    @OnOpen
    public void onOpen( @PathParam(value="token")String token) {
        this.token = token;
        Object object = redisUtil.get(token);
        LoginUser loginUser = (LoginUser)object;
        SysLog sysLog = new SysLog();
        BeanUtils.copyProperties(loginUser, sysLog);
        sysLog.setOperator(loginUser.getUserId()+"/"+loginUser.getUserName());
        sysLog.setModule("系统");
        sysLog.setVoNum("USER");
        sysLogService.insert(sysLog);
    }

    @OnClose
    public void onClose() {
        LoginUser loginUser = (LoginUser)redisUtil.get(token);
        SysLog sysLog = new SysLog();
        BeanUtils.copyProperties(loginUser, sysLog);
        sysLog.setType("退出");
        sysLog.setTime(new Date());
        sysLog.setOperator(loginUser.getUserId()+"/"+loginUser.getUserName());
        sysLog.setModule("系统");
        sysLog.setVoNum("USER");
        sysLogService.insert(sysLog);
    }


}
